<?php

namespace App\Http\Controllers\Backend;

use App\Http\Requests\Backend\EditSchoolAdmin;
use App\Http\Requests\Backend\StoreSchoolAdmin;
use App\Http\Resources\Backend\SchoolAdminResource;
use App\Models\AdminLog;
use App\Models\School;
use App\Models\SchoolAdmin;
use Illuminate\Http\Request;
use Spatie\Permission\Models\Role;

/**
 * Class SchoolAdminController
 * @package App\Http\Controllers\Backend
 * @author zjw
 */
class SchoolAdminController extends BackendController
{
    /**
     * @param Request $request
     * @return \Illuminate\Http\Resources\Json\AnonymousResourceCollection
     */
    public function index(Request $request)
    {
        $schoolAdmins = SchoolAdmin::orderBy('created_at', 'desc')
            ->with(["school", "roles"])
            ->schoolIdIs($request->school_id)
            ->phoneLike($request->phone)
            ->paginate($request->size);
        return SchoolAdminResource::collection($schoolAdmins);
    }

    /**
     * @param StoreSchoolAdmin $request
     * @return SchoolAdminResource|array
     * 新增管理员
     */
    public function store(StoreSchoolAdmin $request)
    {
        $schoolAdmin = new SchoolAdmin();
        $schoolAdmin->fill($request->all());
        $schoolAdmin->password = $request->password;
        $schoolAdmin->save();
        $roles = Role::whereIn('id', $request->roles)->get();
        $schoolAdmin->syncRoles($roles);
        AdminLog::Log("新增管理员: " . $schoolAdmin->phone);
        return new SchoolAdminResource($schoolAdmin);
    }

    /**
     * @param EditSchoolAdmin $request
     * @param SchoolAdmin $schoolAdmin
     * @return SchoolAdminResource
     * 编辑管理员
     */
    public function update(EditSchoolAdmin $request, SchoolAdmin $schoolAdmin)
    {
        $schoolAdmin->fill($request->all());
        $schoolAdmin->save();
        $roles = Role::whereIn('id', $request->roles)->get();
        $schoolAdmin->syncRoles($roles);
        AdminLog::Log("编辑管理员: " . $schoolAdmin->phone);
        return new SchoolAdminResource($schoolAdmin);
    }

    /**
     * @param Request $request
     * @param $id
     * @return SchoolAdminResource|array
     * 重置管理员密码
     */
    public function refresh(Request $request, $id)
    {
        if (!$request->password) return $this->fail('请输入新密码');
        $schoolAdmin = SchoolAdmin::query()->findOrFail($id);
        $schoolAdmin->password = $request->password;
        $schoolAdmin->save();
        AdminLog::Log("重置管理员密码: " . $schoolAdmin->phone);
        return new SchoolAdminResource($schoolAdmin);
    }

    /**
     * @param $schoolId
     * @return array
     * 新增/编辑学校管理员 - 切换学校
     */
    public function show($schoolId)
    {
        return [
            'admins' => School::query()->findOrFail($schoolId)->activeAdmins,
            'roles'  => Role::query()->where('guard_name', 'school')->where('school_id', $schoolId)->get()
        ];
    }
}
